const express = require('express');
const router = express.Router();

// 摄像头配置相关的API路由
function setupConfigRoutes(pool) {
  // 获取摄像头映射数据
  router.get('/api/configs', async (req, res) => {
    try {
      const result = await pool.query(
        `SELECT 
          c.id,
          c.config_name,
          COALESCE(
            json_agg(
              json_build_object(
                'channel_id', ch.channel_id,
                'camera_id', ch.camera_id
              )
            ) FILTER (WHERE ch.channel_id IS NOT NULL),
            '[]'
          ) as mappings
        FROM Configs c
        LEFT JOIN Channels ch ON c.id = ch.config_id
        GROUP BY c.id, c.config_name
        ORDER BY c.id DESC`
      );
      res.json(result.rows);
    } catch (error) {
      console.error('获取映射数据错误:', error);
      res.status(500).json({ error: error.message });
    }
  });

  // 创建新的摄像头配置
  router.post('/api/configs', async (req, res) => {
    try {
      const { config_name } = req.body;
      
      if (!config_name) {
        return res.status(400).json({ error: '配置名称不能为空' });
      }
      
      // 检查配置名称是否已存在
      const configExists = await pool.query('SELECT * FROM Configs WHERE config_name = $1', [config_name]);
      if (configExists.rows.length > 0) {
        return res.status(400).json({ error: '配置名称已存在' });
      }
      
      // 插入新配置
      const result = await pool.query(
        'INSERT INTO Configs (config_name) VALUES ($1) RETURNING id, config_name',
        [config_name]
      );
      
      res.status(201).json({ 
        message: '配置创建成功', 
        config: result.rows[0] 
      });
    } catch (error) {
      console.error('创建配置错误:', error);
      res.status(500).json({ error: '创建配置失败' });
    }
  });

  // 删除摄像头配置
  router.delete('/api/configs/:id', async (req, res) => {
    try {
      const { id } = req.params;
      
      // 检查配置是否存在
      const configExists = await pool.query('SELECT * FROM Configs WHERE id = $1', [id]);
      if (configExists.rows.length === 0) {
        return res.status(404).json({ error: '配置不存在' });
      }
      
      // 使用事务处理
      const client = await pool.connect();
      try {
        await client.query('BEGIN');
        
        // 先删除与该配置相关的映射关系
        await client.query('DELETE FROM Channels WHERE config_id = $1', [id]);
        
        // 删除配置
        await client.query('DELETE FROM Configs WHERE id = $1', [id]);
        
        await client.query('COMMIT');
        
        res.json({ 
          message: '配置删除成功',
          id: id 
        });
      } catch (transactionError) {
        await client.query('ROLLBACK');
        throw transactionError;
      } finally {
        client.release();
      }
    } catch (error) {
      console.error('删除配置错误:', error);
      res.status(500).json({ error: '删除配置失败' });
    }
  });

  // 更新摄像头映射配置（支持PUT方法）
router.put('/api/configs/:configId/mappings', async (req, res) => {
  try {
    const { configId } = req.params;
    const { mappings } = req.body;
    
    // 先删除该配置ID下的所有现有映射
    await pool.query('DELETE FROM Channels WHERE config_id = $1', [configId]);
    
    // 插入新的映射数据
    if (mappings && mappings.length > 0) {
      for (const mapping of mappings) {
        if (mapping.channel_id) {
          await pool.query(
            'INSERT INTO Channels (config_id, channel_id, camera_id) VALUES ($1, $2, $3)',
            [configId, mapping.channel_id, mapping.camera_id]
          );
        }
      }
    }
    
    res.json({ success: true, message: '映射配置更新成功' });
  } catch (error) {
    console.error('更新摄像头映射错误:', error);
    res.status(500).json({ error: error.message });
  }
});

  // 返回router对象
  return router;
}

module.exports = setupConfigRoutes;